import time
from machine import Pin,I2C, UART
import _thread
import bmp280
import ssd1306

uart = UART(2, baudrate=115200, rx=18,tx=17,timeout=10)
def run():
    global da
    global t
    t=0
    da = 0
    try:
        while(1):
            da=da+1
            f = open("date"+str('%06d' % da)+".txt",'r')
            f.close()
    except:
        f = open("date"+str('%06d' % da)+".txt",'a')
        f.write('气压计数据记录\n')
        f.write("记录时间:  原始温度和气压:  高度:\n")
        f.close()
    i2c = I2C(sda=Pin(14), scl=Pin(13))
    b = bmp280.BMP280(i2c)
    def mainapm():
        global t
        f = open("date"+str('%06d' % da)+".txt",'a')
        t=t+1
        y = b.get()
        p = b.getPress()
        tp = b.getTemp()
        adjusted_pressure = p * (1.0 - 0.0065 * tp / 273.15) ** (-5.257)# 温度补偿
        h = ((101325 / adjusted_pressure) ** (1 / 5.257) - 1) * (tp + 273.15) / 0.0065# 根据修正后的气压计算高度
        dat = (str(t/10)+"  "+str(y)+"  "+str(h)+"\n")
        uart.write("记录时间: "+str(t/10)+" 原始温度和气压: "+str(y)+" 高度: "+str(h)+"\n")
        oled.fill(0)
        oled.text("time: "+str(t/10)+"s", 0, 0)
        oled.text("T:"+str(y[0])+"C", 0, 10)
        oled.text("P:"+str(y[1])+"Pa", 0, 20)
        oled.text("HA:"+str(h)+"m", 0, 30)
        oled.show()
        f.write(dat.encode('utf-8'))
        #print(h)
        f.close()
    while(True):
        time.sleep_ms(100)
        _thread.start_new_thread(mainapm,())

uart.write("高度计系统就绪\n")
i2c = I2C(scl=Pin(15),sda=Pin(16))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.text(("Waiting to start"), 0, 10)
oled.show()
while(1):
    
    time.sleep_ms(100)
    umsg = uart.readline()
    if(umsg):
        umsg = umsg.decode('utf-8')
        if(umsg =='start'):
            run()
            break

